package com.example.chat.service.impl;

import com.dragonsoftbravo.libs.IOCloseUtils;
import com.dragonsoftbravo.libs.Opr;
import com.dragonsoftbravo.libs.PssLogFactory;
import com.example.chat.service.CodeMessageService;
import org.slf4j.Logger;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * @author pq
 * @date 2022/8/16 19:49
 * @description
 * @modified
 **/
@Service
public class CodeMessageServiceImpl implements CodeMessageService {

    private Properties codeProperties;

    private static Logger ERROR=PssLogFactory.getErrorLog();

    private static Logger DEBUG=PssLogFactory.getDebugLog();

    /**
     * @author pq
     * @description 项目启动时加载配置文件
     * @param
     * @return void
     * @date 2022/8/16 20:11
     */
    @PostConstruct
    public void init() {
        InputStream is = null;
        try {
            codeProperties = new Properties();
            is = this.getClass().getClassLoader().getResourceAsStream("properties/codemessage.properties");
            codeProperties.load(is);
        } catch (IOException e) {
            ERROR.error(e.getMessage(), e);
            throw new RuntimeException("code message init fail");
        } finally {
            IOCloseUtils.close(is);
        }
    }

    @Override
    public String message(String code) {
        return codeProperties.getProperty(code);
    }

    @Override
    public <T> Opr<T> fail(String operator, String code) {
        DEBUG.debug("operator " + operator + ",result code " + code);
        return fail(code);
    }

    @Override
    public <T> Opr<T> failWithMessage(String message, String code) {
        Opr<T> operationResult = new Opr<>();
        operationResult.setCode(code);
        operationResult.fail(message);
        return operationResult;
    }

    private <T> Opr<T> fail(String code) {
        Opr<T> operationResult = new Opr<>();
        String message = message(code);
        operationResult.setCode(code);
        operationResult.fail(message);
        return operationResult;
    }
}
